<?php

namespace app\api\controller;

use app\common\controller\Api;
use Exception;
use addons\epay\library\Service;
use fast\Http;
use think\Log;
use app\common\model\Pay;
use app\common\model\activity\Activity;
use app\common\model\activity\ActivityOrder;
use app\common\model\bb\Order as ModelBbOrder;
use app\common\model\goods\Goods as GoodsGoods;
use app\common\model\goods\Spec;
use app\common\model\Order as ModelOrder;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\order\Order;
use app\common\model\order\Total;
use app\common\model\raise\Attached;
use app\common\model\raise\Order as RaiseOrder;
use app\common\model\service\Order as ServiceOrder;
use app\common\model\service\order\Info;
use app\common\model\User as ModelUser;
use app\common\model\UserGroup;
use think\Db;
use think\Queue;

/**
 * 微信支付接口
 */
class Wechat extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';


    protected $app_id;
    protected $app_secret;

    public function __construct()
    {
        $this->app_id = 'wxe04dc0591908ba28';
        $this->app_secret = '6a8e16092d8ef30fd17d0ae04f7e796d';
    }

    public function getAccessToken()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->app_id . '&secret=' . $this->app_secret;
        $result = json_decode(Http::get($url), true);
        return $result;
    }

    /**
     * 支付成功回调
     */
    //微信回调
    public  function notify()
    {
        $data = file_get_contents('php://input');
        Log::write('验证支付：' . $data);
        // $data='{"id":"8033a089-09ec-50e5-9454-d291155b4679","create_time":"2024-12-05T09:35:09+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"SNyVqkLw9DSkFfiqCGnuhyFtdQPiZaZtr/mrupz6q3RLMTCcHI/5EfRDXisd8y1jclbi1oCD6F8W8f8Kmv9Xwp5+KQGhqATu298XFX6Q6P7lGLrAetwmkpjH6OJTwx8W8pYeGjsNggFQjJg7cy0HAN4N913L/cDaQ1k0Zgiqrjo4hc549o4wC/H8rK2tIV5wIYopfIr72fDenILWGwDnKE0gyM4sNmUgVZ63QwR+rNyDQTYZNSHjPM0JGBRqrC1/2e4VdH5J3T7fnWVOWBvx0M+2QVAC3d6YiXmY6Mf9HSSIFbwFDQaoKHkeTYzl9wUsttWdS2YL6ObvAzwJ02sD+TYHHpyXOPiCfn9nwNme61YQkfWVNn3iobB/ut65Qa4tZWFFsa9bUByGH7htIMe3ahvVe88MFFEFQCRAcoVrSh33PkNdRcbxAJyrwUQN4WRb8QH2gS3zr3Q9foyvztCUnAAhHY7TNQZnf2g4yjZtrMr8gg8AnSEDE4pFsG4rLSPjwZ5cvQRUN6iOSi/I9UxcnKSxGI2FHRLdv2/8WhXUpyIZfpCBMB/fMg7dmWVfH8BY5usteqp2OG/tuw==","associated_data":"transaction","nonce":"zmi7Xz9q2Gxi"}}';
        $data = json_decode($data, true);
        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        // php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            
            // $APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'wM4jV7zL8cZ2bF4aL4aQ9tS6rB3fZ5oV');
            Log::write('支付成功：' . $orderData);
            // $orderData ='{"mchid":"1635149963","appid":"wx1c2ddbc154bece77","out_trade_no":"XX202212081422119380","transaction_id":"4200001642202212085961916819","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"OTHERS","attach":"order","success_time":"2022-12-08T14:22:21+08:00","payer":{"openid":"of5sB5sZ4gSQQM6wY6h6KQp1hiWA"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}';
            // Db::name('pay_log')->insert(['data' => $orderData]);
            $orderData = json_decode($orderData, true);

//            var_dump($orderData);exit();
            if ($orderData['trade_state'] == 'SUCCESS') {
                $order_sn = $orderData['out_trade_no']; //商户订单号
                $transaction_id = $orderData['transaction_id']; //微信订单号
                $attach = $orderData['attach']; //微信订单号
                // 启动事务
                Db::startTrans();
                try {
                    $order = Info::where('sn', $order_sn)->where('paytime', null)->find();

                    if (!$order) {
                        return true;
                    }
                    $orderInfo = ServiceOrder::get($order['order_id']);
                    /*业务处理*/
                    switch ($attach) {
                        case 'order':
                            if ($orderInfo->status == 0) {
                                ServiceOrder::update(['code' => code(), 'status' => '1'], ['id' => $order['order_id']]);
                            }
                            Info::where('id', $order['id'])->update(['transaction_id' => $transaction_id, 'paytime' => time()]);
                            $mark = "您已成功预约，请按时到达预定地点";
//                            $this->auth->template_push($orderInfo['id'], 0, $mark);

                            $actiontime = strtotime($orderInfo->actiontime);
                            // $endtime = $actiontime + $order->time * 3600;
                        
                            $delay = ($actiontime - 15 * 60) - time();
                       
                            queue('app\common\job\TemplateMessage', $orderInfo, $delay, 'message');
                            break;
                        case 'renewal':
                            $escort = ModelUser::get($orderInfo->escort_id);
                            $group = UserGroup::column('id,proportion');
                            $proportion = $group[$escort->group_id];
                            $commission = bcmul($order->renewal_amount, bcdiv($proportion, 100, 2), 2);
                            Info::where('id', $order['id'])->update(['transaction_id' => $transaction_id, 'paytime' => time(), 'commission' => $commission]);
                            $orderInfo->save([
                                'total_amount' => $orderInfo->total_amount + $order->renewal_amount,
                                'pay_amount' => $orderInfo->pay_amount + $order->renewal_amount,
                                'commission' => $orderInfo->commission + $commission,
                            ]);
                            break;
                    }


                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return;
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return $e->getMessage();
                }
            }
        }
    }
    //退款回调地址
    public static function refund_notify()
    {

        $notifiedData = file_get_contents('php://input');
        Log::write('验证退款：' . $notifiedData);
        // $notifiedData = '{"id":"01785df1-2670-5d3e-990a-37e1584c62e3","create_time":"2023-03-30T16:20:28+08:00","resource_type":"encrypt-resource","event_type":"REFUND.SUCCESS","summary":"退款成功","resource":{"original_type":"refund","algorithm":"AEAD_AES_256_GCM","ciphertext":"ftDRCZz0Ea/Dkv8SE0xs/yXbVkwKTLuwUQZWoGup7AYRIl2ixjCHBe8RrjIlmYmxmAvhSmOgojAmZtzPvYFQib7ZSeBUSQQbkhy3pKjyRZ8wPXM7skCVU8VUK4TpKFesW5k6pcPVBFlGoPQ/dAotMvZ/1i11JDmY+yc1FsMNaV1V+zQ7VDQMifRApqyDs6okS2DuQEPoSq1a7SJu9BLTVjqaIOeQoTfnfgBz9GD2p+exixw6TW9M8ot2cutrXikcW5uYuoVeALHfk0E8/U2fPcdsjwptxdyREU5DnOnvk2sovWLF8D9xkk0drqV4f4FsTfVspgXZWkMtL9AW6OoGx1rAwCikdbSLqgWiqmGudKF693hDbOrgr7gF2GY8JkVwKpb3PTWjz3fVXWTMyR6qL3AwRz6HPgyNR4xz5ytmkz3NKXmVAo2JlRX7o262A5C6cymEI8wfh+QiA3Im+RTPcwQw1sSA/sH7hsTdDBW2JwVGnw+fmyDKMweqzkQNYfixigE=","associated_data":"refund","nonce":"Ux8v3JPRtnAH"}}';
        $data = json_decode($notifiedData, true);

        $nonceStr = $data['resource']['nonce'];
        $associatedData = $data['resource']['associated_data'];
        $ciphertext = $data['resource']['ciphertext'];
        $ciphertext = base64_decode($ciphertext);
        //php>7.1,为了使用这个扩展，你必须将extension=php_sodium.dll添加到php.ini
        if (function_exists('\sodium_crypto_aead_aes256gcm_is_available') && \sodium_crypto_aead_aes256gcm_is_available()) {
            //$APIv3_KEY就是在商户平台后端设置是APIv3秘钥
            $orderData = \sodium_crypto_aead_aes256gcm_decrypt($ciphertext, $associatedData, $nonceStr, 'HVcnpalfopaSXbROX8DU5x9XlTw0VgMV');
            Log::write('退款成功：' . $orderData);

            $orderData = json_decode($orderData, true);
            if ($orderData['refund_status'] == 'SUCCESS') {
                $transaction_id = $orderData['transaction_id']; //退款单号
                $order_sn = $orderData['out_trade_no']; //商户订单号
                // 启动事务
                Db::startTrans();
                try {
                    $order = Info::where('sn', $order_sn)->find();
                    if (!$order) {
                        return true;
                    }
                    $orders = ServiceOrder::get($order['order_id'], ['escort', 'user']);

                    ServiceOrder::cancelOrder($orders, $transaction_id);

                    Db::commit();
                    //应答微信支付已处理该订单的通知
                    return;
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    Log::error($e->getMessage());
                    return $e->getMessage();
                }
            }
        }
    }
}
